package com.cicoding.config;

import java.text.SimpleDateFormat;
import java.util.*;

import com.uhf.alm.CabinetAlgorithm;
import com.uhf.alm.CabinetAlgorithm.IT_MODE;
import com.uhf.alm.Rfmodels;
import com.uhf.alm.TagModel;
import com.uhf.api.cls.ErrInfo;
import com.uhf.api.cls.ReadListener;
import com.uhf.api.cls.Reader;
import com.uhf.api.cls.Reader.AntPower;
import com.uhf.api.cls.Reader.AntPowerConf;
import com.uhf.api.cls.Reader.ConnAnts_ST;
import com.uhf.api.cls.Reader.HardwareDetails;
import com.uhf.api.cls.Reader.Inv_Potl;
import com.uhf.api.cls.Reader.Inv_Potls_ST;
import com.uhf.api.cls.Reader.Mtr_Param;
import com.uhf.api.cls.Reader.READER_ERR;
import com.uhf.api.cls.Reader.ReaderVersion;
import com.uhf.api.cls.Reader.Region_Conf;
import com.uhf.api.cls.Reader.SL_TagProtocol;
import com.uhf.api.cls.Reader.TAGINFO;
import com.uhf.listener.ReadExceptionListener;

/**
 * 不停循环测试柜子模式，20秒读情况，并统计超过10秒没重复读到的标签
 * @author Administrator
 *
 */
public class test_cabinetalgo{

    int AntCount = 16;
    String ReaderAddr ="192.168.1.100";// "COM81:921600";//若接串口读写器地址
   // String ReaderAddr ="COM4";
    Reader Jreader;
    Vector<String> allTags_V=new Vector<String>();
    Map<String,Long> TagTime=new HashMap<String,Long>();
    long st=0;
    CabinetAlgorithm CA;
    String testmsg="";
    int[] Uants=new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};

    public boolean testinitreader() {
        // 创建读写器，传入读写器地址串口或者网口，天线口总个数
        // READER_ERR

        Jreader=new Reader();
        READER_ERR er = Jreader.InitReader_Notype(ReaderAddr, AntCount);
        System.out.println(er.toString());
        if(er!=READER_ERR.MT_OK_ERR)
            return false;
        //获取硬件信息
        HardwareDetails val = Jreader.new HardwareDetails();
        er = Jreader.GetHardwareDetails(val);
        //获取版本信息
        ReaderVersion rdrver = Jreader.new ReaderVersion();
        Jreader.ParamGet(Mtr_Param.MTR_PARAM_READER_VERSION, rdrver);

        System.out.println("module:" + val.module.toString() + "\r\nsoftwareVer:" +
                rdrver.softwareVer + "\r\nhardwareVer:" + rdrver.hardwareVer);

        //获取可配置的最大功率，最小功率
        int[] maxpower = new int[1];
        maxpower[0]=0;
        Jreader.ParamGet(Mtr_Param.MTR_PARAM_RF_MAXPOWER, maxpower);
        System.out.println("max:" + maxpower[0]);
        int[] minpower = new int[1];
        minpower[0]=0;
        Jreader.ParamGet(Mtr_Param.MTR_PARAM_RF_MINPOWER, minpower);
        System.out.println("min:" + minpower[0]);

        AntPowerConf apcf2 = Jreader.new AntPowerConf();
        er = Jreader.ParamGet(Mtr_Param.MTR_PARAM_RF_ANTPOWER, apcf2);
        for (int i = 0; i < apcf2.antcnt; i++) {
            System.out.print("antid:" + apcf2.Powers[i].antid);
            System.out.print(" rp:" + apcf2.Powers[i].readPower);
            System.out.print(" wp:" + apcf2.Powers[i].writePower);
            System.out.println();
        }

        //设置北美频段   可以根据实际修改
        Region_Conf rcf1 = Region_Conf.RG_NA;
        er = Jreader.ParamSet(Mtr_Param.MTR_PARAM_FREQUENCY_REGION, rcf1);

        //设置是否检测天线，如果需要使用不可检测的天线（即无法检测天线是否连接在天线端口上）需要此项设置。
        er = Jreader.ParamSet(Mtr_Param.MTR_PARAM_READER_IS_CHK_ANT, new int[] { 0 });
        return true;

    }


    public void TestCabinetAlgorithm() throws Exception
    {
        //***************************
        //柜子算法参数，这个需要技术支持人员修改。
        TagModel tm=new TagModel();
        tm.setGen2Target(2);// A 0，B 1，A-B 2，B-A 3
        tm.setS2_AInstruct(true);//S2->A  true 启用，false 不启用
        List<Rfmodels> lrflist=new ArrayList<Rfmodels>();

        Rfmodels rf1=new Rfmodels();
        rf1.setCount(3);// 次数 需>=1
        rf1.setQval(-1);//-1 自动 0-15 为静态Q
        rf1.setTime(2000);//天线驻留时间
        rf1.setRfModel("RF_MODE_7");
        lrflist.add(rf1);

        rf1=new Rfmodels();
        rf1.setCount(5);// 次数 需>=1
        rf1.setQval(3);//-1 自动 0-15 为静态Q
        rf1.setTime(4000);//天线驻留时间
        rf1.setRfModel("RF_MODE_13");
        lrflist.add(rf1);

        tm.setrflist(lrflist);
        //******************************
        CA=new CabinetAlgorithm(Jreader,3300,tm);// 3300 是功率值，可以根据实际修改
        CA.addReadExceptionListener(REL);//添加的是柜子算法的异常处理
        CA.addReadListener(RL);

        testmsg="";
        allTags_V.clear();

        int[] ants=null;//天线数组，数组元素为对应的物理天线号，从1开始。可以根据实际修改
        String antstr="";

        ConnAnts_ST cast = Jreader.new ConnAnts_ST();

        Reader.READER_ERR re = Jreader.ParamGet(Mtr_Param.MTR_PARAM_READER_CONN_ANTS, cast);

        if(re==READER_ERR.MT_OK_ERR&&cast.antcnt>0)
        {
            ants=new int[cast.antcnt];
            for(int i=0;i<ants.length;i++)
            {	ants[i]=cast.connectedants[i];antstr+=String.valueOf(ants[i])+" ";}
        }
        else
        {
            ants=this.Uants;//天线数组，数组元素为对应的物理天线号，从1开始。可以根据实际修改
            for(int i=0;i<ants.length;i++)
            {  antstr+=String.valueOf(ants[i])+" ";}
        }

        int option=0x0002<<8;
        System.out.println("TestCabinetAlgorithm>>>>>>>>>>>>>>>>>>>>>>antlsit "+antstr);
        re = CA.Preparationforwork(IT_MODE.IT_MODE_BOXV1);//准备工作必须调用
        System.out.println("------Preparationforwork---- " + re);
        if(re!=READER_ERR.MT_OK_ERR)
            throw new Exception("error1");
        re =CA.AsyncStartReading_IT(IT_MODE.IT_MODE_BOXV1, ants, ants.length, option);//开始盘点
        System.out.println("------AsyncStartReading_IT---- " + re);
        if(re!=READER_ERR.MT_OK_ERR)
            throw new Exception("error2");
        int readtimeout=20*1000;//测试时间为xx秒，可根据实际修改,0不限制

        st=System.currentTimeMillis();

        do
        {
            try {
                Thread.sleep(4);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }while(readtimeout==0||System.currentTimeMillis()-st<readtimeout);
        System.out.print(testmsg);

        re =CA.AsyncStopReading_IT();
        System.out.println("------AsyncStopReading_IT---- " + re);
        if(re!=READER_ERR.MT_OK_ERR)
        {	 re =CA.AsyncStopReading_IT();
            System.out.println("------AsyncStopReading_IT----2222222222222 " + re);
            if(re!=READER_ERR.MT_OK_ERR)
                throw new Exception("error3");
        }


        System.out.println("TestCabinetAlgorithm<<<<<<<<<<<<<<<<<<<<<<<<<:"+
                (System.currentTimeMillis()-st)+"\r\n");
    }

    ReadListener RL=new ReadListener()
    {

        @Override
        public void tagRead(Reader r, final TAGINFO[] tag) {
            // TODO Auto-generated method stub

            for(int i=0;i<tag.length;i++)
            {
                long nowt=System.currentTimeMillis();
                String key=Reader.bytes_Hexstr(tag[i].EpcId);
                if(!allTags_V.contains(key))
                {

                    allTags_V.add(key);//标签epcid，其它数据项参考api文档

                    testmsg="last new tag "+String.valueOf(allTags_V.size())
                            +" :"+key+" ant:"+tag[i].AntennaID+" rssi:"+tag[i].RSSI
                            +"  time:"+String.valueOf(nowt-st);
                    //System.out.println(testmsg);
                    TagTime.put(key, nowt);
                    // TagTime.put(key, 1);
                    //*
                    //if(key.contains("8064"))
                    System.out.println("new tag "+String.valueOf(allTags_V.size())
                            +" :"+key+" ant:"+tag[i].AntennaID+" rssi:"+tag[i].RSSI
                            +"  time:"+String.valueOf(System.currentTimeMillis()-st));
                    //*/
                }
                else
                {
                    //*
                    // Date date1 = new Date();
                    // SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
                    // if(key.contains("8064"))
                    {
                        long ct=System.currentTimeMillis()-TagTime.get(key);
                        String msg="";
                        if(ct>10000)
                        {	 msg="!!!!!!!!!!!!!!!!!!!";
                            System.err.println("tag "+(allTags_V.indexOf(key)+1)+" :"+key+
                                    " ant:"+tag[i].AntennaID+" rssi:"+tag[i].RSSI+" time:"+String.valueOf(ct)+msg);
                        }
                        else
                            System.out.println("tag "+(allTags_V.indexOf(key)+1)+" :"+key+
                                    " ant:"+tag[i].AntennaID+" rssi:"+tag[i].RSSI+" time:"+String.valueOf(ct)+msg);
                        //  System.out.println("tag "+allTags_V.indexOf(key)+" :"+key
                        //          +"  time:"+dateFormat.format(date1));
                    }

                    //*/
                    TagTime.put(key, nowt);
                }
            }
        }
    };

    ReadExceptionListener REL=new ReadExceptionListener()
    {

        @Override
        public void tagReadException(Reader r, READER_ERR re, String errmsg) {
            // TODO Auto-generated method stub
            //如果需要可在此处记录异常日志
            System.out.println(r.GetReaderAddress() + "--异常信息:" + re.toString());
            ErrInfo ei = new ErrInfo();
            r.GetLastDetailError(ei);

            System.out.println("last errcode:" + Integer.toHexString(ei.derrcode) +"  errstr:"+ ei.errstr);
            //处理异常（可以断开，重连接读写器，再启动工作）
            CA.AsyncStopReading_IT();
            Jreader.CloseReader();
        }

    };

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.out.println("java.library.path:" + System.getProperty("java.library.path"));
        System.out.println("java.version:" + System.getProperty("java.version"));
        System.out.println("java.specification.version:" + System.getProperty("java.specification.version"));
        System.out.println("java.vm.name:" + System.getProperty("java.vm.name"));
        System.out.println("sun.arch.data.model:" + System.getProperty("sun.arch.data.model"));
        System.out.println("os.arch:" + System.getProperty("os.arch"));
        System.err.println("ModeAlgorithmlib-test2");

        // *
        try {
            if(!System.getProperty("os.arch").contains("64"))
            {
                //32位系统需要这个支持库
                System.loadLibrary("ACE");
            }
            System.loadLibrary("PCOMM");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        int c=0;
        long st=System.currentTimeMillis();
        test_cabinetalgo tc=new test_cabinetalgo();
        if(tc.testinitreader()){

            while (true){
                System.out.println("excute count:"+String.valueOf(++c)+
                        " time:"+String.valueOf(System.currentTimeMillis()-st));
                try {
                    tc.TestCabinetAlgorithm();

                    //break;

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    System.out.println(e.getMessage()+" to closerreader");
                    tc.Jreader.CloseReader();
                    break;
                }
            }

        }
        else
            System.out.println("init reader failed!!!");
    }
}
